package com.zq.it.cms.web.back;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alibaba.fastjson.JSON;
import com.zq.it.cms.common.CmsException;
import com.zq.it.cms.common.Constants;
import com.zq.it.cms.common.Servlets;
import com.zq.it.cms.domain.Role;
import com.zq.it.cms.domain.User;
import com.zq.it.cms.service.RoleService;
import com.zq.it.cms.service.UserService;

/**
 * @author zhengqiang
 * @description 用户权限
 */
@Controller
@RequestMapping("/users")
public class UserController {
	
	@Autowired
	private UserService userService;
	@Autowired
	private RoleService roleService;
	
	@RequestMapping(value = "/list")
	public String list(ModelMap model){
		Map<String, Object> params = Servlets.getSearchParam();
		PageRequest page = Servlets.getPageRequest();
		Page<User> pageData = userService.findPageByParams(params, page);
		model.put("pageData", pageData);
		return "users/list";
	}
	
	@RequestMapping(value = "/create")
	public String create(Long id, ModelMap model){
		User user = null;
		if(id != null){
			user = userService.findById(id);
		}
		if(user == null){
			user = new User();
		}
		List<Role> roleList = roleService.findAllByParams(null);
		model.put("user", user);
		model.put("roleList", roleList);
		model.put("userRoles", user.getRoleList());
		model.put(Constants.OPRT, Constants.OPRT_CREATE);
		return "users/form";
	}
	@RequestMapping(value = "/edit")
	public String edit(Long id, ModelMap model){
		User user = null;
		if(id != null){
			user = userService.findById(id);
		}
		if(user == null){
			throw new CmsException("没有找到这个用户");
		}
		List<Role> roleList = roleService.findAllByParams(null);
		model.put("user", user);
		model.put("roleList", roleList);
		model.put("userRoles", user.getRoleList());
		model.put(Constants.OPRT, Constants.OPRT_EDIT);
		return "users/form";
	}
	
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public String save(User user, ModelMap model){
		System.err.println(JSON.toJSON(user));
		return "redirect:create";
	}
	
}
